<template>
<div>
   <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"></TopFilter>
       <FilterTable
       ref="table"
        :columns="columns"
        :params="fetchParams"
        :fetchapi="fetchapi"
        :datakey="'records'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="selectChange">
        <template slot="controls" slot-scope="props">
            <multiuse-button size="small" type="primary" icon="el-icon-check" :click="qiyong.bind()" :disabled="disableds">启用</multiuse-button>
            <multiuse-button size="small" type="primary" icon="el-icon-close" :click="tingyong.bind()" :disabled="disableds">禁用</multiuse-button>
            <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
            <multiuse-button type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
            <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">下载模板</multiuse-button>
            <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()">导入</multiuse-button>
        </template>
          </FilterTable>
      <BaseDialog
      :visible.sync="visibleAdd"
      :title="'首保PDI设置（油）新增'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <!--保存在AddForm-->
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>


    <BaseDialog :visible.sync="visibleEdit" :title="'首保PDI设置（油）编辑'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="closeEdit" @save="saveEdit" :rowData="rowData" ></EditForm>
    </BaseDialog>
        <BaseDialog :visible.sync="showImport" icon="el-icon-upload" :closable="false" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editsav1()" url="/api/cms_claimfac/rPGuaranteeOil/importExcel"/>
    </BaseDialog>
</div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';//字典的引入
import {selectPageByExample}  from '@/api/claim/factory/guaranteeOil';//点击搜索 分页查询
import {deleteOne,getListForExport,downloadModel,exporturl}  from '@/api/claim/factory/guaranteeOil';//逻辑删除单条数据
import {piliangqiyong}  from '@/api/claim/factory/guaranteeOil';//批量启用
import { piliangtingyong}  from '@/api/claim/factory/guaranteeOil';//批量停用
import AddForm from './AddForm.vue';//新增
import EditForm from './EditForm.vue';//编辑
import { exportExcelFile } from '@/utils/index';//导出
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';//导入
export default {
  mixins: [dictionary],
    components: {
    //Vehicle,
    AddForm,
    EditForm,
    importExcel,
  },
  data(){
    return{
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      fetchapi: selectPageByExample,
      visibleAdd: false,
      rowData: {},
      visibleEdit : false,
      disableds: true,
      showImport: false,
      collapse:true

    }

  },
  methods:{
      editsav1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
      },
      //下载模板
      downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then((res) => {
          console.log('666');
          console.log(res);
          exportExcelFile(res.data, '首保PDI设置(油)导入模板');
          this.exportLoading = false;
        });
      });
    },
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    saveEdit() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeEdit() {
      this.visibleEdit = false;
    },
    async chuqi() {
    const res = await getPart(); //等待getPart()方法执行后返回数据给 res 然后再对返回的数据进行操作
    if (res.resultCode == 200) {
        this.topFilterInit.find((x) => x.fieldName == 'typeId').initialValue = '';//默认初始值为空
        this.topFilterInit.find((x) => x.fieldName == 'typeId').itemList = res.data.map((y) => ({ text: y.name, value: y.code }));//????
      }

    },
        // 删除
    async delFun(val) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.res = await deleteOne(val.guaranteeId);
          if (this.res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })
    },

    // Excel更新导入
    showImportFun() {
      this.showImport = true;
      this.fetchParams = { ...this.fetchParams };
    },

    //搜索数据
    topFilterInitFun() {
    return [

        {type: 'INPUT', label: '车型代码', fieldName: 'modelCode', placeholder: '请输入车型代码...', initialValue: ''},
        {type: 'INPUT', label: '车型名称', fieldName: 'modelName', placeholder: '请输入车型名称...', initialValue: ''},
      {type: 'SELECT',label: '类型',fieldName: 'type',placeholder: '请选择类型...',
         itemList: this.createDictList('5593'),initialValue: ''
      }
    ]
  },
  creatHeader() {
     return [
       {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
          },

        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          /*render:重新渲染 重新定义这个单元格显示的内容*/
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.delFun(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '状态', dataIndex: 'ptStatusStr', sorter: true },
        { title: '类型', dataIndex: 'type', sorter: true,
          render: props => {    //编码转汉字  反显
            return <span>{this.createDictText(props.row.type, '5593')}</span>;
        } },
        { title: '车型编码', dataIndex: 'modelCode', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
         { title: '工时单价', dataIndex: 'labPrice', sorter: true },
        { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true },
        { title: '修改人', dataIndex: 'updatedBy', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true },
        { title: '备注', dataIndex: 'remarks', sorter: true },
        ]
       },
       //导出
     async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000127' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },
        showErrorList(response) {
      if (response.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '导入完成!' });
        this.fetchParams = { ...this.fetchParams };//????
        this.fileList = [];
        this.loading = false;
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: response.errMsg });
        this.loading = false;
      }
    },
     handleExceed(error) {
      this.loading = false;
    },
    beforeUpload() {
      this.loading = true;
    },
    //批量启用
    async qiyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.guaranteeId + ',';
        });
        console.log(str);
        const res = await piliangqiyong({ ids: str, status: 1 });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行启用！' });
      }
    },
    //批量停用
    async tingyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.guaranteeId + ',';
        });
        const res = await piliangtingyong({ ids: str, status: 0 });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行禁用！' });
      }
    },
        add() {
      this.visibleAdd = true;
    },
        closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
        edit() {
      this.visibleEdit = true;
    },


    emitFun(val) {
      this.rowData = val;
      this.visibleEdit = true;
    },


    close() {
      this.visible = false;
    },

    /*可以带值用 可多值*/
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible = false;
    },
    //搜索获取数据
    changeHandle(val) {
      /*刷新表格 用它*/
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      console.log(val);
    },
}
  }

</script>
<style lang="less" scoped></style>
